import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import { 
  Card, 
  Button, 
  Alert, 
  Spin, 
  Modal, 
  Typography, 
  Space, 
  Row, 
  Col 
} from "antd";
import { 
  DownloadOutlined, 
  CheckOutlined, 
  CloseOutlined 
} from "@ant-design/icons";
import { fetchApproveData, submitApproval } from "../api/ragApi";

const { Title, Text } = Typography;

const ApprovePage = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [actionLoading, setActionLoading] = useState(false);
  const location = useLocation();

  // 从URL中获取token
  const queryParams = new URLSearchParams(location.search);
  const token = queryParams.get("token");

  useEffect(() => {
    if (!token) {
      setError("Token is required");
      setLoading(false);
      return;
    }

    const fetchData = async () => {
      try {
        const response = await fetchApproveData(token);
        setData(response.data);
      } catch (err) {
        setError(err.message || "Failed to fetch data");
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [token]);

  const handleAction = async (status) => {
    setActionLoading(true);
    try {
      await submitApproval(token, status);
      Modal.success({
        title: "Success",
        content: `File has been ${status === "approved" ? "approved" : "rejected"} successfully`,
      });
      // 重新获取最新数据
      const response = await fetchApproveData(token);
      setData(response.data);
    } catch (err) {
      Modal.error({
        title: "Error",
        content: err.message || "Failed to submit action",
      });
    } finally {
      setActionLoading(false);
    }
  };

  if (!token) {
    return (
      <Modal
        title="Missing Token"
        open={true}
        footer={null}
        closable={false}
      >
        <Alert
          message="Error"
          description="Token is required in the URL parameters"
          type="error"
          showIcon
        />
      </Modal>
    );
  }

  if (loading) {
    return (
      <div style={{ textAlign: "center", padding: "50px" }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error) {
    return (
      <Alert
        message="Error"
        description={error}
        type="error"
        showIcon
        style={{ margin: "20px" }}
      />
    );
  }

  return (
    <div style={{ padding: "20px", maxWidth: "800px", margin: "0 auto" }}>
      <Card 
        title={<div style={{ textAlign: "center", width: "100%" }}><Title level={3} style={{ margin: 0 }}>Document Approval</Title></div>}
        style={{ borderRadius: "8px", boxShadow: "0 4px 12px rgba(0,0,0,0.1)" }}
      >
        <Space direction="vertical" size="middle" style={{ width: "100%" }}>
          <Row gutter={[16, 16]}>
            <Col span={8}>
              <Text strong>Creator:</Text>
            </Col>
            <Col span={16}>
              <Text>{data.creator_email}</Text>
            </Col>
            
            <Col span={8}>
              <Text strong>RAG Owner:</Text>
            </Col>
            <Col span={16}>
              <Text>{data.rag_owner}</Text>
            </Col>
            
            <Col span={8}>
              <Text strong>Knowledge:</Text>
            </Col>
            <Col span={16}>
              <Text>{data.knowledge_base_id}</Text>
            </Col>
            
            <Col span={8}>
              <Text strong>Status:</Text>
            </Col>
            <Col span={16}>
              <Text type={data.status === "1" ? "success" : data.status === "2" ? "danger" : "warning"}>
                {data.status === "0" ? "Pending" : data.status === "1" ? "Approved" : "Rejected"}
              </Text>
            </Col>
            
            <Col span={8}>
              <Text strong>Comment:</Text>
            </Col>
            <Col span={16}>
              <Text>{data.comment}</Text>
            </Col>
          </Row>
          
          <Card type="inner" title={<div style={{ textAlign: "center", width: "100%" }}><Text strong style={{ fontSize: 16 }}>Files</Text></div>}>
            <Space direction="vertical" style={{ width: "100%" }}>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />}
                href={data.origin_url}
                target="_blank"
                block
              >
                Download Original File
              </Button>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />}
                href={data.file_url}
                target="_blank"
                block
              >
                Download Converted File
              </Button>
            </Space>
          </Card>
          
          {data.status === "0" && (
            <div style={{ textAlign: "center", marginTop: "24px" }}>
              <Space>
                <Button
                  type="primary"
                  icon={<CheckOutlined />}
                  size="large"
                  loading={actionLoading}
                  onClick={() => handleAction("approved")}
                  style={{ width: "120px" }}
                >
                  Approve
                </Button>
                <Button
                  danger
                  icon={<CloseOutlined />}
                  size="large"
                  loading={actionLoading}
                  onClick={() => handleAction("rejected")}
                  style={{ width: "120px" }}
                >
                  Reject
                </Button>
              </Space>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default ApprovePage;
